package com.hooper.dp.utils;

import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Optional;

/**
 * @author Tim Hooper
 * @version 1.0
 * @time 2023/02/26/16:53
 */
@Component
@RequiredArgsConstructor
public class IDWorker {

    private  final StringRedisTemplate stringRedisTemplate;

    private final Long BASE_TIME_STAMP = 1577808000L;


    /**
     * 使用redis生成全局唯一ID
     * @param key
     * @return
     */
    public Long nextId(String key){
        LocalDateTime now = LocalDateTime.now();
        long res = (now.toEpochSecond(ZoneOffset.UTC) - BASE_TIME_STAMP) << 32;
        String date = DateTimeFormatter.ofPattern("yyyy:MM:dd").format(now);
        Long increment = stringRedisTemplate.opsForValue().increment(key + date);
        return res | Optional.ofNullable(increment).orElse(0L);
    }
}
